<template>
	<page-wrapper :page-path="'/pages/index/index'" :navLeft="'logo'" :navBackgroundColor="primaryColor">
		<view class="index-container">

			<!-- 收支概览 -->
			<view class="overview-card">
				<!-- 日期选择器 -->
				<view class="date-picker">
					<view class="year-month" @click="showDatePicker">
						<text>{{ currentYear }}年</text>
						<view class="month-selector">
							<text style="font-weight: bold;">{{ currentMonth }}月</text>
							<uni-icons type="bottom" size="14" :color="textColor"></uni-icons>
						</view>
					</view>
				</view>

				<!-- 收支数据 -->
				<view class="balance-info">
					<view class="balance-item">
						<text class="balance-label">收入</text>
						<text class="balance-value">{{ income.toFixed(2) }}</text>
					</view>
					<view class="balance-item">
						<text class="balance-label">支出</text>
						<text class="balance-value">{{ expense.toFixed(2) }}</text>
					</view>
				</view>
			</view>

			<!-- 使用原生日期选择器代替uni-calendar -->
			<uni-popup ref="datePopup" type="bottom" style="z-index: 999;">
				<view class="date-picker-popup">
					<view class="picker-header">
						<text @click="cancelDatePicker">取消</text>
						<text @click="confirmDatePicker">确定</text>
					</view>
					<picker-view class="picker-view" :value="[currentYear - startYear, currentMonth - 1]"
						@change="onDatePickerChange">
						<picker-view-column>
							<view class="picker-item" v-for="(year, index) in yearArray" :key="index">{{ year }}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(month, index) in monthArray" :key="index">{{ month }}月
							</view>
						</picker-view-column>
					</picker-view>
				</view>
			</uni-popup>

			<!-- 快捷菜单 -->
			<view class="quick-menu">
				<view class="menu-item" v-for="(item, index) in menuItems" :key="index" @click="navigateTo(item.path)">
					<view class="menu-icon" :style="{ backgroundColor: item.bgColor }">
						<uni-icons :type="item.icon" size="24" color="#333"></uni-icons>
					</view>
					<text class="menu-text">{{ item.text }}</text>
				</view>
			</view>

			<!-- 账单列表 -->
			<view class="bill-list-container">
				<view class="pull-down-image-wrapper">
					<view class="pull-down-image-container" :style="{height: `${Math.max(0, pullDistance)}rpx`}">
						<image class="pull-down-image" src="/static/images/background.jpg" mode="aspectFill"></image>
					</view>
				</view>
				<scroll-view scroll-y class="bill-list" @scrolltolower="onLoadMore"
					refresher-enabled :refresher-triggered="refresherTriggered" @refresherrefresh="onRefresh"
					:refresher-threshold="150" refresher-background="transparent" refresher-default-style="none"
					@refresherpulling="onPulling" @refresherrestore="onPullRestore" @refresherabort="onPullAbort">
					<!-- 自定义下拉刷新文字 -->
					<view slot="refresher" class="refresh-slot" :style="{opacity: pullDistance > 0 ? 1 : 0, height: pullDistance > 0 ? '120rpx' : '0rpx'}">
						<view class="refresh-indicator" :style="{transform: `scale(${pullScale})`}">
							<text class="refresh-text" :class="{'refresh-text-active': refresherTriggered}">
								{{ refresherTriggered ? '刷新中...' : (pullDistance > 150 ? '松开刷新' : '下拉刷新') }}
							</text>
						</view>
					</view>
					
					<!-- 账单日期分组 -->
					<view class="bill-date-group" v-for="(group, date) in groupedBills" :key="date">
						<!-- 日期和总支出 -->
						<view class="date-header">
							<view class="date-info">
								<text class="date-text">{{ formatDate(date) }}</text>
								<text class="weekday">{{ getWeekday(date) }}</text>
							</view>
							<text class="date-total" :class="{ 'income-color': isDayIncome(group) }">
								{{ isDayIncome(group) ? '收入：' : '支出：' }}{{
									Math.abs(calculateDayBalance(group)).toFixed(2) }}
							</text>
						</view>

						<!-- 当日账单列表 -->
						<view class="bill-item" v-for="(bill, index) in group" :key="index"
							@click="viewBillDetail(bill)">
							<view class="bill-left">
								<view class="category-icon"
									:style="{ backgroundColor: bill.category && bill.category.color ? bill.category.color + '40' : '#FFE7B240' }">
									<image :src="bill.category.icon" class="category-icon-image"
										v-if="bill.category && bill.category.icon"></image>
								</view>
								<text class="category-name">{{ bill.category ? bill.category.name : '未分类' }}</text>
							</view>
							<!-- 备注 -->
							<view class="bill-remark">
								<text class="bill-remark-text">{{ bill.remark }}</text>
							</view>
							<view class="bill-right">
								<text class="bill-amount" :class="{ 'income-color': isIncome(bill) }">{{ isIncome(bill)
									? '+' : '-' }}{{ bill.amount.toFixed(2) }}</text>
							</view>
							<image :src="bill.platform.icon" class="platform-icon-image"
								v-if="bill.platform && bill.platform.icon"></image>
						</view>
					</view>

					<!-- 无数据提示 -->
					<view class="no-data" v-if="Object.keys(groupedBills).length === 0">
						<text>暂无账单数据</text>
					</view>

					<!-- 加载更多 -->
					<view class="load-more" v-if="bills.length > 0">
						<text v-if="hasMore">上拉加载更多</text>
						<text v-else>没有更多数据了</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</page-wrapper>
</template>

<script>
import { themeMixin } from '@/utils/theme.js';
import PageWrapper from '@/components/page-wrapper/page-wrapper.vue';
import { queryTransactions } from '@/api/transaction';
import { useDateStore } from '@/store/dateStore';

export default {
	components: {
		PageWrapper
	},
	mixins: [themeMixin], // 混入主题工具
	data() {
		const currentDate = new Date();
		const currentYear = currentDate.getFullYear();
		const startYear = currentYear - 5;
		const endYear = currentYear + 5;

		return {
			income: 0.00,
			expense: 0.00,
			tempYear: currentYear, // 临时存储选择的年份
			tempMonth: currentDate.getMonth() + 1, // 临时存储选择的月份
			startYear: startYear,
			yearArray: Array.from({ length: endYear - startYear + 1 }, (_, i) => startYear + i),
			monthArray: Array.from({ length: 12 }, (_, i) => i + 1),
			menuItems: [
				{ text: '收支', icon: 'list', bgColor: '#FFE7B2', path: '/pages/bills/bills' },
				{ text: '预算', icon: 'wallet', bgColor: '#FFE7B2', path: '/pages/budget/budget' },
				{ text: '资产管家', icon: 'star', bgColor: '#FFE7B2', path: '/pages/assets/assets' },
				{ text: '购物清单', icon: 'cart', bgColor: '#FFE7B2', path: '/pages/shopping/shopping' },
				{ text: '更多', icon: 'more-filled', bgColor: '#FFE7B2', path: '/pages/more/more' }
			],
			// 账单数据
			bills: [],
			loading: false,
			page: 1,
			pageSize: 10,
			total: 0,
			hasMore: true, // 是否还有更多数据
			refresherTriggered: false, // 下拉刷新状态
			pullDistance: 0, // 下拉距离
			pullScale: 1, // 下拉缩放比例
		}
	},
	computed: {
		// 使用Pinia store中的年月
		currentYear() {
			return this.dateStore.currentYear;
		},
		currentMonth() {
			return this.dateStore.currentMonth;
		},
		// 按日期分组的账单
		groupedBills() {
			const grouped = {};
			this.bills.forEach(bill => {
				const date = bill.transactionDate.split(' ')[0]; // 只取日期部分
				if (!grouped[date]) {
					grouped[date] = [];
				}
				grouped[date].push(bill);
			});
			return grouped;
		},
		// 获取dateStore
		dateStore() {
			return useDateStore();
		}
	},
	onLoad() {
		// 初始化临时年月为store中的值
		this.tempYear = this.currentYear;
		this.tempMonth = this.currentMonth;

		// 从API获取账单数据
		this.fetchBillData();

		// 监听账单更新事件
		uni.$on('bill_updated', this.handleBillUpdated);
	},
	onUnload() {
		// 组件卸载时移除事件监听
		uni.$off('bill_updated', this.handleBillUpdated);
	},
	methods: {
		// 处理账单更新事件
		handleBillUpdated() {
			this.refreshData();
		},

		// 下拉刷新处理
		onPullDown() {
			this.refreshData();
		},

		// 刷新数据
		refreshData() {
			this.page = 1;
			this.bills = []; // 清空现有数据
			this.hasMore = true; // 重置加载更多状态
			this.fetchBillData();
		},

		// 处理下拉过程中的动态效果
		onPulling(e) {
			// 获取下拉的距离
			const distance = e.detail.dy;
			this.pullDistance = distance;
			
			// 计算阻尼效果，使下拉越来越费劲
			// 开始时正常下拉，超过100px后开始增加阻力
			if (distance <= 50) {
				this.pullScale = 1;
			} else {
				// 使用对数函数模拟阻力增加
				// 距离越大，缩放比例越小，给人一种拉弹弓的感觉
				const dampingFactor = Math.log10(distance - 90) / 2;
				this.pullScale = Math.max(0.6, 1 - dampingFactor * 0.1);
			}
		},

		// 处理下拉刷新
		async onRefresh() {
			this.refresherTriggered = true;
			this.pullScale = 1; // 重置缩放
			await this.refreshData();
			
			// 增加刷新时间，提供更好的视觉反馈
			setTimeout(() => {
				this.refresherTriggered = false;
				this.pullDistance = 0;
				// 刷新成功提示
				uni.vibrateShort(); // 添加触感反馈
				// uni.showToast({
				// 	title: '刷新成功',
				// 	icon: 'success',
				// 	duration: 500
				// });
			}, 1500);
		},

		// 处理触底加载更多
		onLoadMore() {
			if (!this.loading && this.hasMore) {
				this.page++;
				this.fetchBillData();
			}
		},

		// 获取账单数据
		async fetchBillData() {
			if (this.loading) return;

			this.loading = true;
			try {
				// 构建当月的开始和结束日期时间戳（秒）
				const year = this.currentYear;
				const month = this.currentMonth;

				const startDate = Math.floor(new Date(year, month - 1, 1).getTime() / 1000);
				const endDate = Math.floor(new Date(year, month, 0, 23, 59, 59).getTime() / 1000);

				console.log('查询日期范围:', new Date(startDate * 1000), new Date(endDate * 1000));
				console.log('当前选择的年月:', year, month);

				const res = await queryTransactions({
					page: this.page,
					pageSize: this.pageSize,
					startDate: startDate,
					endDate: endDate
				});

				if (res && res.data && (res.data.code === 200 || res.data.code === 1 || res.data.code === 0)) {
					// 修正数据结构的获取方式
					const data = res.data.code === 0 ? res.data.data :
						(res.data.code === 200 ? res.data.data : res.data);
					const records = data.records;
					const totalRecords = data.total || 0;

					// 如果是第一页，直接替换数据；否则追加数据
					if (this.page === 1) {
						this.bills = records || [];
					} else {
						this.bills = [...this.bills, ...(records || [])];
					}

					this.total = totalRecords;

					// 判断是否还有更多数据
					this.hasMore = this.bills.length < this.total;

					// 使用API返回的统计数据
					if (this.page === 1 && data.totalIncome !== undefined && data.totalExpense !== undefined) {
						this.income = data.totalIncome;
						this.expense = data.totalExpense;
					} else {
						// 如果API没有返回统计数据，则计算总收入和支出
						this.calculateTotalAmount();
					}
				}
			} catch (error) {
				console.error('获取账单数据失败:', error);
				uni.showToast({
					title: '获取账单数据失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},

		// 判断是否为收入
		isIncome(bill) {
			// 根据category.spend判断：0是收入，1是支出
			return bill.category && bill.category.spend === 0;
		},

		// 判断某一天是否盈利
		isDayIncome(bills) {
			const dayBalance = this.calculateDayBalance(bills);
			return dayBalance > 0; // 总收入大于总支出表示盈利
		},

		// 计算某一天的净收入（盈利）或净支出（支出）
		calculateDayBalance(bills) {
			const totalIncome = bills.reduce((sum, bill) => {
				if (this.isIncome(bill)) {
					return sum + bill.amount;
				}
				return sum;
			}, 0);
			const totalExpense = bills.reduce((sum, bill) => {
				if (!this.isIncome(bill)) {
					return sum + bill.amount;
				}
				return sum;
			}, 0);
			return totalIncome - totalExpense;
		},

		// 格式化日期显示
		formatDate(dateStr) {
			const date = new Date(dateStr);
			return `${date.getMonth() + 1}月${date.getDate()}日`;
		},

		// 获取星期几
		getWeekday(dateStr) {
			const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			const date = new Date(dateStr);
			return weekdays[date.getDay()];
		},

		// 计算某一天的总支出
		calculateDayExpense(bills) {
			return bills.reduce((sum, bill) => {
				// 如果不是收入，则计入支出
				if (!this.isIncome(bill)) {
					return sum + bill.amount;
				}
				return sum;
			}, 0);
		},

		// 计算总收入和支出
		calculateTotalAmount() {
			let totalIncome = 0;
			let totalExpense = 0;

			this.bills.forEach(bill => {
				if (this.isIncome(bill)) {
					totalIncome += bill.amount;
				} else {
					totalExpense += bill.amount;
				}
			});

			this.income = totalIncome;
			this.expense = totalExpense;
		},

		// 查看账单详情
		viewBillDetail(bill) {
			uni.navigateTo({
				url: `/pages/bill-detail/bill-detail?id=${bill.id}`
			});
		},

		// 页面导航
		navigateTo(path) {
			uni.navigateTo({
				url: path
			});
		},

		// 显示日期选择器
		showDatePicker() {
			// 确保临时年月与当前选择的年月一致
			this.tempYear = this.currentYear;
			this.tempMonth = this.currentMonth;
			this.$refs.datePopup.open();
		},

		// 日期选择确认
		confirmDatePicker() {
			this.$refs.datePopup.close();
			// 更新store中的年月
			this.dateStore.setDate(this.tempYear, this.tempMonth);
			// 重新加载数据
			this.fetchBillData();
		},

		// 日期选择取消
		cancelDatePicker() {
			this.$refs.datePopup.close();
		},

		// 日期选择器 picker-view 变化
		onDatePickerChange(e) {
			const selectedYear = this.yearArray[e.detail.value[0]];
			const selectedMonth = this.monthArray[e.detail.value[1]];
			this.tempYear = selectedYear;
			this.tempMonth = selectedMonth;
		},

		// 处理下拉恢复（松开但未触发刷新）
		onPullRestore() {
			console.log('下拉恢复');
			// 重置下拉距离，隐藏图片
			this.pullDistance = 0;
		},
		
		// 处理下拉中断
		onPullAbort() {
			console.log('下拉中断');
			// 重置下拉距离，隐藏图片
			this.pullDistance = 0;
		}
	}
}
</script>

<style lang="scss">
.index-container {
	background-color: $background-color;
	position: relative;
	display: flex;
	flex-direction: column;

	// 收支概览卡片
	.overview-card {
		background-color: $primary-color;
		padding: 20rpx 10rpx;
		flex-shrink: 0;
		/* 防止压缩 */
		display: flex;

		.date-picker {
			// margin-bottom: 40rpx;
			display: flex;
			justify-content: start;
			flex: 1;

			.year-month {
				display: flex;
				flex-direction: column;
				align-items: center;
				font-size: 32rpx;
				color: $text-color;
				font-weight: 400;

				.month-selector {
					display: flex;
					align-items: center;
					margin-top: 10rpx;
					margin-left: 20rpx;
					padding: 5rpx 20rpx;
					background-color: rgba(255, 255, 255, 0.2);
					border-radius: 30rpx;
				}
			}
		}

		.balance-info {
			display: flex;
			flex: 3;
			justify-content: space-between;
			padding: 0 20rpx;

			.balance-item {
				display: flex;
				flex-direction: column;

				.balance-label {
					font-size: 28rpx;
					color: $text-color;
					margin-bottom: 10rpx;
					font-weight: 300;
				}

				.balance-value {
					font-size: 40rpx;
					font-weight: 400;
					color: $text-color;
				}
			}
		}
	}

	// 日期选择器弹窗样式
	.date-picker-popup {
		background-color: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		overflow: hidden;

		.picker-header {
			display: flex;
			justify-content: space-between;
			padding: 30rpx;
			border-bottom: 1px solid $border-color;

			text {
				font-size: 32rpx;
				color: $text-color;

				&:last-child {
					color: $primary-color;
					font-weight: bold;
				}
			}
		}

		.picker-view {
			width: 100%;
			height: 500rpx;

			.picker-item {
				line-height: 80rpx;
				text-align: center;
				font-size: 32rpx;
			}
		}
	}

	// 快捷菜单
	.quick-menu {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
		height: 150rpx;
		flex-shrink: 0;
		/* 防止压缩 */

		.menu-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 20%;

			.menu-icon {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 16rpx;
			}

			.menu-text {
				font-size: 22rpx;
				color: $text-color;
			}
		}
	}

	// 账单列表
	.bill-list-container {
		flex: 1;
		/* 占据剩余空间 */
		background-color: #fff;
		position: relative;
		
		.pull-down-image-wrapper {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			z-index: 1;
			overflow: hidden;
			
			.pull-down-image-container {
				width: 100%;
				height: 0; /* 初始高度为0 */
				overflow: hidden;
				transition: height 0.1s ease-out;
				
				.pull-down-image {
					width: 100%;
					height: 100%;
					object-fit: cover; /* 确保图片填满容器 */
					object-position: center bottom; /* 从底部开始显示 */
				}
			}
		}

		.bill-list {
			box-sizing: border-box;
			height: calc(100vh - 100rpx - 240rpx - 240rpx);
			/* 减去导航栏、底部栏、概览卡片和快捷菜单的高度 */
			position: relative;
			z-index: 2;
			
			// 自定义下拉刷新样式
			.refresh-slot {
				width: 100%;
				height: 120rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				overflow: hidden;
				background: transparent;
				
				.refresh-indicator {
					transition: transform 0.1s ease-out;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					position: relative;
					background-color: rgba(255, 255, 255, 0.7);
					padding: 10rpx 30rpx;
					border-radius: 30rpx;
					
					&::before {
						content: '';
						position: absolute;
						width: 200%;
						height: 4rpx;
						background-color: #e0e0e0;
						top: -20rpx;
						transform: scaleX(calc(0.5 + 0.5 * var(--pull-scale, 1)));
						opacity: calc(var(--pull-distance, 0) / 200);
					}
					
					.refresh-text {
						font-size: 30rpx;
						color: #666;
						font-weight: 500;
						transition: all 0.2s;
						transform: scale(1);
						
						&.refresh-text-active {
							color: $primary-color;
							transform: scale(1.1);
						}
					}
				}
			}

			.bill-date-group {
				padding: 0 40rpx;
				margin-bottom: 40rpx;

				.date-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1px solid $border-color;

					.date-info {
						display: flex;
						align-items: center;

						.date-text {
							font-size: 28rpx;
							color: $text-color;
							font-weight: bold;
							margin-right: 20rpx;
						}

						.weekday {
							font-size: 24rpx;
							color: $text-color-lighter;
						}
					}

					.date-total {
						font-size: 28rpx;
						color: $text-color;
						font-weight: bold;

						&.income-color {
							color: #4CAF50;
							/* 盈利时显示绿色 */
						}
					}
				}

				.bill-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx 0;
					border-bottom: 1px solid $border-color;

					.bill-left {
						display: flex;
						align-items: center;

						.category-icon {
							width: 80rpx;
							height: 80rpx;
							border-radius: 50%;
							display: flex;
							justify-content: center;
							align-items: center;
							margin-right: 30rpx;

							.category-icon-image {
								width: 60rpx;
								height: 60rpx;
							}
						}

						.category-name {
							font-size: 32rpx;
							color: $text-color;
						}
					}

					.bill-remark {
						padding: 0 20rpx;
						flex: 1;
						display: flex;
						justify-content: end;

						.bill-remark-text {
							font-size: 28rpx;
							color: $text-color-lighter;
						}
					}

					.platform-icon-image {
						width: 35rpx;
						height: 35rpx;
						margin-left: 20rpx;
					}

					.bill-right {
						.bill-amount {
							font-size: 32rpx;
							font-weight: bold;
							color: $text-color;

							&.income-color {
								color: #4CAF50;
							}
						}
					}
				}
			}

			.no-data {
				padding: 100rpx 0;
				text-align: center;
				color: $text-color-lighter;
			}

			.load-more {
				padding: 30rpx 0;
				text-align: center;
				color: $text-color-lighter;
				font-size: 24rpx;
			}
		}
	}
}
</style>
